package com.study.graph.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class IPUtil {

    public static String getLocalIpName(){
        String ipAddr = null;
        List<String> ips = new ArrayList<String>();
        Enumeration allNetInterfaces = null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress ip = null;

        while (allNetInterfaces.hasMoreElements())
        {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            //System.out.println(netInterface.getName());
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements())
            {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address )
                {
                    //System.out.println("本机的IP = " + ip.getHostAddress());
                    if(!(ip.getHostName().toString().equalsIgnoreCase("127.0.0.1")))
                        ips.add(ip.getHostAddress()+"_"+ip.getHostName().toString() );
                }
            }
        }
        if(ips.size()>0){
            ipAddr = ips.get(0);
        }else{
            ipAddr = ""+System.currentTimeMillis();
        }
        return ipAddr;
    }

    public static String getLocalIp() {
        String ipAddr = null;
        List<String> ips = new ArrayList<String>();
        Enumeration allNetInterfaces = null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress ip = null;

        while (allNetInterfaces.hasMoreElements())
        {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            //System.out.println(netInterface.getName());
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements())
            {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address )
                {
                    //System.out.println("本机的IP = " + ip.getHostAddress());
                    if(!(ip.getHostName().toString().equalsIgnoreCase("127.0.0.1")))
                        ips.add(ip.getHostAddress());
                }
            }
        }
        if(ips.size()>0){
            ipAddr = ips.get(0);
        }else{
            ipAddr = "127.0.0.1";
        }
        return ipAddr;
    }
}
